 

package com.zdkj.subway.rca.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.subway.rca.dto.SwCkClearRulesDTO;
import com.zdkj.subway.rca.dto.in.OneSidedSales;
import com.zdkj.subway.rca.dto.in.OneSidedSalesDTO;
import com.zdkj.subway.rca.entity.SwCkClearRules;
import com.zdkj.subway.rca.service.SwCkClearRulesService;
import com.zdkj.subway.rca.util.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


/**
 * 清分规则管理
 *
 * @author stw
 * @date 2020-11-08 22:46:57
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swckclearrules" )
@Api(value = "swckclearrules", tags = "清分及划账-清分规则管理")
public class SwCkClearRulesController {

    @Autowired
    private final SwCkClearRulesService swCkClearRulesService;

    /**
     * 运营商下拉列表
     * @return
     */
    @ApiOperation(value = "运营商下拉列表", notes = "运营商下拉列表")
    @GetMapping("/listoperators" )
    public R listoperators() {
        return R.ok(swCkClearRulesService.getServiceMap());
    }

    /**
     * 分页查询
     * @param page 分页对象
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "operators", value = "运营商编码", dataTypeClass = String.class)
            }
    )
    public R getSwCkClearRulesPage(Page page,String startDate, String endDate, String operators) {
        SwCkClearRules swCkClearRules = new SwCkClearRules();
        if(StringUtils.isNotEmpty(startDate)) {
            swCkClearRules.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        if(StringUtils.isNotEmpty(endDate)) {
            swCkClearRules.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        swCkClearRules.setDelFlag("0");

        IPage<SwCkClearRules> iPage =  swCkClearRulesService.page(page, Wrappers.query(swCkClearRules).orderByDesc("BEGIN_TIME"));
        return R.ok(iPage);
    }


    /**
     * 分页查询pageList
     * @param page 分页对象
     * @return
     */
    @ApiOperation(value = "分页查询pageList", notes = "分页查询pageList")
    @GetMapping("/pageList" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
            }
    )
    public R getSwCkClearRulesBPage(Page page,String startDate, String endDate, SwCkClearRules swCkClearRulesDto) {
        SwCkClearRules swCkClearRules = new SwCkClearRules();
        if(StringUtils.isNotEmpty(startDate)) {
            swCkClearRules.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        if(StringUtils.isNotEmpty(endDate)) {
            swCkClearRules.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
		if(StringUtils.isNotEmpty(swCkClearRulesDto.getDataSource())) {
            swCkClearRules.setDataSource(swCkClearRulesDto.getDataSource());
        }
        swCkClearRules.setClearRules(swCkClearRulesDto.getClearRules());
        swCkClearRules.setSubClearRules(swCkClearRulesDto.getSubClearRules());
        swCkClearRules.setOperators(swCkClearRulesDto.getOperators());
        swCkClearRules.setUsedState(swCkClearRulesDto.getUsedState());
        swCkClearRules.setDelFlag("0");

        IPage<SwCkClearRules> iPage =  swCkClearRulesService.page(page, Wrappers.query(swCkClearRules)
                .orderByDesc("BEGIN_TIME"));
        List<SwCkClearRules> records = iPage.getRecords();
        for(SwCkClearRules obj : records){
            obj.setOperators(swCkClearRulesService.getServiceName(obj.getOperators()));
        }
        iPage.setRecords(records);
        return R.ok(iPage);
    }

    /**
     * 通过id查询清分规则管理
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询", hidden = true)
    @GetMapping("/getById" )
    public R getById(Long id) {
        return R.ok(swCkClearRulesService.getById(id));
    }

    /**
     * 新增清分规则管理
     * @param swCkClearRulesDTO 清分规则管理
     * @return R
     */
    @ApiOperation(value = "新增清分规则管理", notes = "新增清分规则管理")
    @SysLog("新增清分规则管理" )
    @PostMapping("/swckclearrulesAdd")
    public R save(@RequestBody SwCkClearRulesDTO swCkClearRulesDTO) {
        return R.ok(swCkClearRulesService.saveSwCkClearRules(swCkClearRulesDTO));
    }

    /**
     * 通过id查询清分规则管理 主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询清分规则管理", notes = "通过id查询清分规则管理")
    @GetMapping("/getDetail/{id}")
    public R getDetailById(@PathVariable("id") Long id) {
        return R.ok(swCkClearRulesService.getDetailById(id));
    }


    /**
     * 修改清分规则管理
     * @param swCkClearRulesDTO 清分规则管理
     * @return R
     */
    @ApiOperation(value = "修改清分规则管理", notes = "修改清分规则管理")
    @SysLog("修改清分规则管理" )
    @PutMapping("/swckclearrulesEdit")
    public R updateById(@RequestBody SwCkClearRulesDTO swCkClearRulesDTO) {
        return R.ok(swCkClearRulesService.updateSwCkClearRules(swCkClearRulesDTO));
    }


    /**
     * 更改使用状态为使用中
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "设为当前使用", notes = "设为当前使用")
    @SysLog("设为当前使用" )
    @GetMapping("/updateUsedStateToUse" )
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_rules_use')" )
    public R updateUsedStateToUse(@RequestParam(value = "ids") List<Long> ids) {
        List<SwCkClearRules> list = new ArrayList<>();
        List<SwCkClearRules> listUpdate = new ArrayList<>();
        for(Long id : ids){
            //把运营商的同时间范围的规则置为暂停使用，因为同一个运营商只能同时保留一个清分比例在使用中
            SwCkClearRules dbSwCkClearRules = swCkClearRulesService.getById(id);

            //查找相同运营商和时间范围的
            SwCkClearRules conditionSwCkClearRules = new SwCkClearRules();
            conditionSwCkClearRules.setBeginTime(dbSwCkClearRules.getBeginTime());
            conditionSwCkClearRules.setEndTime(dbSwCkClearRules.getEndTime());
            conditionSwCkClearRules.setClearRules(dbSwCkClearRules.getClearRules());
            conditionSwCkClearRules.setSubClearRules(dbSwCkClearRules.getSubClearRules());
            conditionSwCkClearRules.setOperators(dbSwCkClearRules.getOperators());
            conditionSwCkClearRules.setDelFlag("0");

            List<SwCkClearRules> subList = swCkClearRulesService.list(Wrappers.query(conditionSwCkClearRules));
            listUpdate.addAll(subList);

            SwCkClearRules swCkClearRules = new SwCkClearRules();
            swCkClearRules.setId(id);
            swCkClearRules.setUsedState("1");
            list.add(swCkClearRules);
        }

        for(SwCkClearRules updateObj : listUpdate){
            updateObj.setUsedState("2"); //暂停使用
        }
        swCkClearRulesService.updateBatchById(listUpdate);

        return R.ok(swCkClearRulesService.updateBatchById(list));
    }

    /**
     * 更改使用状态为暂停使用
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "暂停使用", notes = "暂停使用")
    @SysLog("暂停使用" )
    @GetMapping("/updateUsedStateToStop" )
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_rules_stop')" )
    public R updateUsedStateToStop(@RequestParam(value = "ids") List<Long> ids) {
        List<SwCkClearRules> list = new ArrayList<>();
        for(Long id : ids){
            SwCkClearRules swCkClearRules = new SwCkClearRules();
            swCkClearRules.setId(id);
            swCkClearRules.setUsedState("2");
            list.add(swCkClearRules);
        }

        return R.ok(swCkClearRulesService.updateBatchById(list));
    }
    /**
     * 通过id列表删除清分规则管理
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表删除清分规则管理", notes = "通过id列表删除清分规则管理")
    @SysLog("通过id列表删除清分规则管理" )
    @GetMapping("/removeByIds" )
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_rules_del')" )
    public R removeByIds(@RequestParam(value = "ids") List<Long> ids) {
        List<SwCkClearRules> list = new ArrayList<>();
        for(Long id : ids){
            SwCkClearRules swCkClearRules = new SwCkClearRules();
            swCkClearRules.setId(id);
            swCkClearRules.setDelFlag("1");
            list.add(swCkClearRules);
        }

        return R.ok(swCkClearRulesService.updateBatchById(list));
    }

    /**
     * 导出
     * @param
     * @return
     */
    @ApiOperation(value = "导出", notes = "导出")
    @GetMapping({"/export"})
    @SysLog("清分规则管理-导出")
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_rules_export')")
    public void export(@RequestParam(value = "ids") List<Long> ids, HttpServletResponse response) {
        if(ids == null || ids.isEmpty()){
            return;
        }
      swCkClearRulesService.export(ids,response);
    }

    /**
     * 清分及划账-清分规则管理-系统自动计算按月
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分规则管理-系统自动计算按月，点击“系统自动计算”按钮弹出窗口选择时间(yyyy-MM格式)", notes = "清分及划账-清分规则管理-系统自动计算按月，点击“系统自动计算”按钮弹出窗口选择时间(yyyy-MM格式)")
    @SysLog("清分及划账-清分规则管理-系统自动计算按月" )
    @GetMapping({"/autoComputeMonth"})
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_rules_autoCompute')" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "日期 yyyy-MM格式", dataTypeClass = String.class, required = true)                  
            }
    )    
    public R autoComputeMonth(String startDate) {
        try {
            if (StringUtils.isEmpty(startDate)){
                return R.failed();
            }
            int iYear = Integer.parseInt(startDate.split("-")[0]);
            int iMonth = Integer.parseInt(startDate.split("-")[1]);
            String realStartDate = MyDateUtil.getFirstDayOfMonth(iYear, iMonth);
            String realEndDate = MyDateUtil.getLastDayOfMonth(iYear, iMonth);          

            return R.ok(swCkClearRulesService.autoComputeMonth(realStartDate, realEndDate));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }

    /**
     * 清分及划账-清分规则管理-系统自动计算按天
     * @return R
     */
    @ApiOperation(value = "清分及划账-清分规则管理-系统自动计算按天，点击“系统自动计算”按钮弹出窗口选择时间(yyyy-MM-dd格式)", notes = "清分及划账-清分规则管理-系统自动计算按天，点击“系统自动计算”按钮弹出窗口选择时间(yyyy-MM-dd格式)")
    @SysLog("清分及划账-清分规则管理-系统自动计算按天" )
    @GetMapping({"/autoComputeDay"})
    @PreAuthorize("@pms.hasPermission('sw_ck_clear_rules_autoCompute')" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "日期 yyyy-MM-dd格式", dataTypeClass = String.class, required = true),
                    @ApiImplicitParam(name = "endDate", value = "日期 yyyy-MM-dd格式", dataTypeClass = String.class, required = true)                   
            }
    )
   
    public R autoComputeDay(String startDate, String endDate) {
        try {
            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
                return R.failed();
            }
            return R.ok(swCkClearRulesService.autoComputeDay(startDate, endDate));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed();
        }

    }

    /**
     * 查询返回数据
     * @param
     * @return R
     */
    public List<SwCkClearRulesDTO> selectRules() {
        //todo 如果传参，里边加上条件就行
        return swCkClearRulesService.selectRules();
    }


    /**
     * 系统清分单边销售编辑
     * @param oneSidedSalesDTO 系统清分单边销售编辑
     * @return R
     */
    @ApiOperation(value = "单边销售编辑", notes = "单边销售编辑")
    @SysLog("系统清分单边销售编辑" )
    @PutMapping("/updateOneSidedSales")
    public R updateOneSidedSales(@RequestBody OneSidedSalesDTO oneSidedSalesDTO) {
        return R.ok(swCkClearRulesService.updateOneSidedSales(oneSidedSalesDTO));
    }

    /**
     * 根据日期查询线路
     *
     * @return R
     */
    @ApiOperation(value = "根据日期查询线路", notes = "根据日期查询线路")
    @GetMapping("/getOneSidedLines")
    public R getLineByOperators(String cleanDate) {
        List<OneSidedSales> result = swCkClearRulesService.getLineByOperator(cleanDate);
        return R.ok(result);
    }

}
